package com.jsgt.greekfire.ui.home.entrance.walletList

import android.app.Dialog
import android.content.Intent
import android.text.TextUtils
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.ActivityStackManager
import com.fhx.core.utils.DialogUtil
import com.fhx.core.utils.SharePreferencesUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.*
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.factory.WalletViewModelFactory
import com.jsgt.greekfire.ui.home.entrance.walletList.adapter.WalletAdapter
import com.jsgt.greekfire.common.util.*
import com.jsgt.greekfire.viewmodel.WalletViewModel1
import com.jsgt.greekfire.common.widget.LoadPageHolder
import com.jsgt.greekfire.common.widget.RecyclerViewItemDecoration
import com.jsgt.greekfire.ui.main.MainAtrActivity
import kotlinx.android.synthetic.main.activity_wallet_list.*

/**
 * 钱包列表
 */
class WalletListActivity : BaseActivity() {
    private val walletViewModel1: WalletViewModel1 by lazy {
        ViewModelProvider(
            this,
            WalletViewModelFactory()
        ).get(WalletViewModel1::class.java)
    }
    private var pwdDialog: Dialog? = null
    var curIdentity: IdentityBean? = null
    override fun getLayoutId() = R.layout.activity_wallet_list

    override fun needFitsSystemWindows(): Boolean {
        return false
    }

    private lateinit var loadPageHolder: LoadPageHolder
    override fun main() {
        if (!BuildConfig.DEBUG) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }
        setTitle(R.string.wallet_list)
        val adapter =
            WalletAdapter()
        val list = ArrayList<IdentityBean>()
        val set = WalletManager.getLocalWallets()
        for (bean in set) {
            list.add(bean)
        }
        loadPageHolder = LoadPageHolder(this, title_layout)
        if (list.isEmpty()) {
            loadPageHolder.setLoadState(LoadPageHolder.LoadState.EMPTY)
        }
        adapter.addData(list)
        val decoration = RecyclerViewItemDecoration.Builder(this)
            .color(0) //分割线颜色
            .thickness(resources.getDimensionPixelSize(R.dimen.divider)) //这里是分割线高度
            .firstLineVisible(true)
            .lastLineVisible(true)
            .create()
        recycler_view.addItemDecoration(decoration)
        adapter.itemClickListner = {
//            if (LOGIN_STATUS && WALLET_ADDRESS.endsWith(it.utiAddress.toString())) {
//                ToastUtils.show(getString(R.string.the_same_error))
//            } else {
//                curIdentity = it
//                showInputPwdDialog()
//            }
        }

        recycler_view.adapter = adapter

        walletViewModel1.importWalletData.observe(this, Observer {
            showProgress(false)
            if (it == null) {
                ToastUtils.show(this, getString(R.string.wallet_add_failed))
            } else {
                SharePreferencesUtil.saveString(this, TOKEN_VALUE, it.token)
                LOGIN_STATUS = true
                IS_ACTIVATION = 1
                SharePreferencesUtil.saveInteger(App.context!!, ACTIVATION_STATUS, IS_ACTIVATION)
//                WALLET_ADDRESS = curIdentity!!.utiAddress.toString()
                NetDataManager.logout()
                ActivityStackManager.finishAll()
                val intent = Intent(this, MainAtrActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }
        })
        walletViewModel1.errorLiveData.observe(this, Observer {
            showProgress(false)
        })

    }


    private fun showInputPwdDialog() {
        val contentView = layoutInflater.inflate(R.layout.dialog_input_wallet_pwd, null, false)
        pwdDialog = DialogUtil.show(this, contentView)
        pwdDialog?.setOnDismissListener {
            pwdDialog = null
        }
        pwdDialog?.setCancelable(true)
        pwdDialog?.show()
        contentView.findViewById<TextView>(R.id.check_pwd_tv_cancel).setOnClickListener {
            pwdDialog?.dismiss()
        }

        contentView.findViewById<TextView>(R.id.check_pwd_tv).setOnClickListener {
            val pwd = contentView.findViewById<EditText>(R.id.pwd_et).text.toString().trim()
            if (TextUtils.isEmpty(pwd)) {
                showToast(getString(R.string.input_pwd_error_null))
            } else {
                pwdDialog?.dismiss()
                pwdDialog = null
                val privateKey = AESOperator.getInstance().decryptJni(
                    curIdentity!!.priKey)

                var wallet = YTWalletUtils.generateBip44WalletByPrivateKey(privateKey, pwd)

                if (wallet == null) {
                    ToastUtils.show(mContext!!, getString(R.string.wallet_add_error))
                } else {
                    showProgress(true)

                    walletViewModel1.importWallet(
                        curIdentity!!.identityName.toString(),
                        MD5Util.getMD5(pwd),
                        wallet.address.toString()
                    )
                }

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }
}